<?php
namespace cms\controllers;

use Yii;
use yii\web\Controller;
use app\models\CoreConfig;
use common\component\exception\ErrMap;
use common\models\OperationLog;
use common\models\App;
use common\component\tool\Tool;

class BasicController extends Controller
{
    protected $get;
    protected $post;
    protected $headers;
    protected $session;
    protected $appid;//对外
    protected $app_id;//对内
    protected $comid;
    protected $app_info_id;
    protected $domain;//应用域名 主要用于前段
    protected $template;//应用模板编号 主要用于前段
    protected $lang;//语言参数
    
    /*所有控制器，必须执行的方法 优先于beforeAction前执行*/
    public function init()
    {
        $this->get = Yii::$app->request->get();
        $this->post = Yii::$app->request->post();
        $this->headers = Yii::$app->request->headers;
        $this->session = Yii::$app->session;
        // $this->get['appid'] = 'CMS20192xG12aUi222';
        $this->lang = 'zh';
    }

    public function beforeAction($action)
    {
        // sleep(1);
        $module = $this->module->id;
        $controller = $this->id;
        $action = $this->action->id;
        // echo $module . '-' . $controller . '-' . $action;die;

        if($module == 'frontend'){
            if(isset($_SERVER['HTTP_ORIGIN'])){
                $origin = $_SERVER['HTTP_ORIGIN'];
                array_push(Yii::$app->params['allow_origin'], $origin);
            }else{
                $origin = '*';
            }
        }else{
            $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '*';
        }
        // $allow_origin = array(
        //     '*',
        //     'chrome-extension://pcppojmnbplflaohhidncmdnbkikphkd',
        //     'http://localhost:8080',
        //     'http://10.9.87.104:8080',
        //     'http://10.9.87.12:8080',
        //     'http://10.9.87.101:8081',
        //     'http://ac.super.com',
        //     'http://www.dhqh.com:802',
        //     'http://admin.raysfly.com',
        //     'http://dhqh.horsevision.cn'
        // );
        // P($origin);
        // $origin = '*';
        if(in_array($origin, Yii::$app->params['allow_origin'])){  
            header('Access-Control-Allow-Origin:'.$origin);
            header('Access-Control-Allow-Methods:POST,GET'); 
            header('Access-Control-Allow-Credentials:true');

            /*判断访问的后台模块、还是前台模块*/
            if($module == 'frontend'){//前台模块
                if(isset($this->get['lang'])){
                    $this->lang = $this->get['lang'];
                    Yii::$app->params['lang'] = $this->lang;//主要为了smarty自定义插件能够取到值
                }
                if(isset($this->get['appid'])){
                    $this->appid = $this->get['appid'];
                }
                if(isset($this->post['appid'])){
                    $this->appid = $this->post['appid'];
                }
                if(!empty($this->appid)){
                    $app = App::find()->select(['app_id', 'appid', 'comid', 'app_info_id'])
                                      ->where('appid = :appid', [':appid' => $this->appid])
                                      ->one();
                    if(!is_null($app)){
                        $this->app_id = $app->app_id;
                        $this->app_info_id = $app->app_info_id;
                        $this->comid = $app->comid;
                        Yii::$app->params['app_id'] = $app->app_id;
                        return true;
                    }else{
                        list($errno, $errmsg) = ErrMap::getError(405);//实例不存在
                    }
                    // P($app);
                }


                // $domain = explode(":", $_SERVER['HTTP_HOST'])[0];
                $domain = $_SERVER['HTTP_HOST'];
                // echo $domain;die;
                /*查询配置文件*/
                $coreConfig = CoreConfig::find()->select(['app_id', 'pc_url', 'mobile_url', 'template'])
                                    ->where('pc_url = "http://' . $domain . '" or pc_url = "https://' . $domain . '" or mobile_url = "http://' . $domain . '" or mobile_url = "https://' . $domain . '"')
                                    ->asArray()->one();
                // P($coreConfig);
                if(!empty($coreConfig)){
                    $this->app_id = $coreConfig['app_id'];
                    Yii::$app->params['app_id'] = $coreConfig['app_id'];
                    /*查询APP*/
                    $app = App::find()->select(['app_id', 'appid', 'comid', 'app_info_id'])
                                      ->where('app_id = :app_id', [':app_id' => $this->app_id])
                                      ->one();
                    if(isset($app->app_id)){
                        $this->app_id = $app->app_id;
                        $this->app_info_id = $app->app_info_id;
                        $this->comid = $app->comid;
                        Yii::$app->params['app_id'] = $app->app_id;
                        $this->appid = $app['appid'];
                        if(('http://' . $domain) == $coreConfig['pc_url'] or ('https://' . $domain) == $coreConfig['pc_url']){
                            $this->domain = $coreConfig['pc_url'];
                        }
                        if(('http://' . $domain) == $coreConfig['mobile_url'] or ('https://' . $domain) == $coreConfig['mobile_url']){
                            $this->domain = $coreConfig['mobile_url'];
                        }
                        $this->template = $coreConfig['template'];
                        // P($domain);
                        return true;
                    }else{
                        list($errno, $errmsg) = ErrMap::getError(405);//实例不存在
                    }
                }
                
            }else if($module == 'backend' or $module == 'app-cms'){//后台模块 or 没有写模块
                if($module == 'app-cms' and $controller == 'basic' and $action == 'open-app'){//访问的是本控制器的方法
                    return true;
                }
                if($module == 'backend' and $controller == 'instance' and $action == 'list'){//访问的是所有实例控制器
                    return true;
                }
                /*如果存在appid, 根据appid得到app_id*/
                if(isset($this->get['appid']) or isset($this->post['appid'])){
                    if(isset($this->get['appid'])){
                        $this->appid = $this->get['appid'];
                    }
                    if(isset($this->post['appid'])){
                        $this->appid = $this->post['appid'];
                    }
                    $app = App::find()->select(['app_id', 'comid', 'app_info_id'])
                                      ->where('appid = :appid', [':appid' => $this->appid])
                                      ->one();
                    // P($app);
                    if(isset($app->app_id)){
                        $this->app_id = $app->app_id;
                        $this->app_info_id = $app->app_info_id;
                        $this->comid = $app->comid;
                        Yii::$app->params['app_id'] = $app->app_id;

                        /*根据app_id 获取模板参数*/
                        /*查询配置文件*/
                        $coreConfig = CoreConfig::find()->select(['pc_url', 'mobile_url', 'template'])
                                        ->where('app_id = ' . $app->app_id)
                                        ->asArray()->one();
                        // P($coreConfig);
                        $this->template = $coreConfig['template'];

                        return true;
                    }else{
                        list($errno, $errmsg) = ErrMap::getError(405);//实例不存在
                    }
                }else{
                    list($errno, $errmsg) = ErrMap::getError(405);//实例不存在
                }
            }
        }

        //非合法域
        if(!isset($errno) and !isset($errmsg)){
            list($errno, $errmsg) = ErrMap::getError(404);//访问的文件飞走了
        }
        $args = array(
            'loginid' => 0,
            'loginname' => '',
            'back_code' => $errno,
            'back_info' => $errmsg,
        );
        if(gettype($res = OperationLog::addLog($args)) != 'boolean'){//操作日志
            Yii::$app->end($res);
        };
    }


    /*注释原因： 放到工具类*/
    /*
    操作日志通用参数
    $backInfo['返回码', '返回信息']
    */
    // protected function operationLogArgs($backInfo = ['', ''])
    // {
    //     $args = array(
    //         'loginid' => isset($this->userInfo['admin_id'])?$this->userInfo['admin_id']:'',
    //         'loginname' => isset($this->userInfo['username'])?$this->userInfo['username']:'',
    //         'comid' => isset($this->userInfo['comid'])?$this->userInfo['comid']:'',
    //         'back_code' => $backInfo[0],
    //         'back_info' => $backInfo[1]
    //     );
    //     return $args;
    // }


    /*创建应用,由认证中心调取  注释原因：认证中心直接操作公共库*/
    // public function actionOpenApp()
    // {
    //     $appInfo = '';//开通成功后，存入此
    //     if(Yii::$app->request->isPost){
    //     // if(1){
    //     //     $this->post['appInfoId'] = '88';
    //     //     $this->post['app_name'] = '88';
    //     //     $this->post['comid'] = '00000000';
    //     //     $this->post['buyTime'] = '2';
    //         $app = new App;
    //         if(($appInfo = $app->addApp($this->post)) !== false){
    //             $backInfo = [0, '开通APP实例成功'];//返回信息
    //         }else{
    //             if($app->hasErrors()){
    //                 $backInfo = ErrMap::getError(10005);//返回信息
    //                 $exception = $app->getErrors();//异常信息
    //             }
    //         }

    //     }
    //     // P($appInfo);

    //     if(!isset($backInfo)){
    //         $backInfo = ErrMap::getError(10005);//返回信息
    //     }
    //     if(!isset($exception)){
    //         $exception = '';//异常信息
    //     }
    //     //操作日志
    //     $args = Tool::operationLogArgs($backInfo);
    //     $args['appid'] = isset($appInfo['appid'])?$appInfo['appid']:'';
    //     $args['comid'] = isset($this->post['comid'])?$this->post['comid']:'';
    //     if(gettype( $res = OperationLog::addLog($args, $exception, ['appinfo' => $appInfo]) ) != 'boolean'){
    //         return $res;
    //     };
    // }


    /*取出语言版本  注释原因：数据放到前台了，不需要从后台获取*/
    // public function actionLang()
    // {
    //     return Tool::showRes([0, '获取成功'], Yii::$app->params['lang']);
    // }


}
